﻿<?php
// 视图类
class View {
	// 保存所有模板的列表
	protected $_templates;
	protected $_all_var;
	// 构造时送入模板的文件名
	public function __construct() {
		$this->_templates = array();
		$this->_all_var = array();
	}
	// 设定模板作用域中的变量
	public function set($name, $val) {
		$this->_all_var[$name] = $val;
	}
	// 获取模板作用域中的变量
	public function get($name) {
		return $this->_all_var[$name];
	}
	public function load($tpl_name) {
		trim($tpl_name, '/\\');
		$path = HOME.DS.'views'.DS.$tpl_name;
		$this->_templates[] = $path;
	}
	// 显示页面
	public function display() {
		// 将 _all_var 中的变量放到当前运行环境中
		extract($this->_all_var, EXTR_OVERWRITE);
		// 将载入的模板全部输出
		foreach ($this->_templates as $t) {
			if (!file_exists($t)) {
				throw new Exception("Cannot find template file: $t");
			}
			// ob_start();
			include "$t";
			// $page_content = ob_get_clean();
			// echo $page_content;
		}
	}
	
	// Configuration:
	// 
	// array (
	//   "base" => "MVC/main/index",
	//   "total" => "20",
	//   "start" => "0",
	//   "per_page" => PER_PAGE
	// );
	//
	// URL : main/index/20/0,  main/index/20/5,... 
	public static function gen_page_link($conf) {
		// 构造基地址
		$url = 'http://'.$_SERVER["HTTP_HOST"].'/'.trim($conf['base'], '\\/');
		$link = '<p class="page_link">';
		$start = $conf["start"];
		$total = $conf["total"];
		$per = $conf["per_page"];
		$current = floor($start / $per) + 1;
		if ($current > 1) {
			$link .= '<a href="'.$url.'/'.$total.'/'.
					($start - $per).'"> Prev</a>';
		} else {
			$link .= 'Prev';
		}
		for ($i = 1; $i <= $total; $i++) {
			if ($i != $current) {
				$link .= '<a href="'.$url.'/'.$total.'/'.
					(($i - 1) * $per).'"> - '.$i.' </a>';
			} else {
				$link .= " - $i ";
			}
		}
		if ($current < $total) {
			$link .= '<a href="'.$url.'/'.$total.'/'.
					($start + $per).'"> - Next</a>';
		} else {
			$link .= ' - Next';
		}
		$link .= '</p>';
		return $link;
	}

	static public function format_errors($warning, $errors) {
		if (empty($errors)) {
			return "";
		}
		$ret = '<p class="error">'.$warning.'</p>';
		foreach ($errors as $e) {
			$ret .= '<p class="error_reason">  - '.$e.'</p>';
		}
		return $ret;
	}

	// 生成评论列表
	static public function format_comments($comments) {
		$disp = NULL;
		foreach ($comments as $c) {
			if (!empty($c["comment_date"]) && !empty($c["name"])) {
				$format = "Y 年 n 月 j 日 G:i";
				$date = date($format, strtotime($c["comment_date"]));
				$byline = "<span><strong><i>$c[name] - $c[email] </i></strong>
                            $date</span>";
				$disp .= "<p class=\"comment\">$byline$c[body]</p>";
			} else {
				$byline = NULL;
				$admin = NULL;
			}
		}
		if (!isset($disp)) {
			$disp = "";
		}
		return $disp;
	}
}